import pygame
import netstream
import sys
import event
from common import *
from dispatcher import Dispatcher
from event_looper import EventLooper
from filter import ServerReceiveFilter, SockProcessFilter,\
    ServerEventHandleFilter, SerialFilter, ServerSendFilter, ServerUpdateFilter
from filter import DeSerialFilter
from filter import TestPrintFilter
import time
import logging
import player
from event_producer import EventProducer, ServerEventIt

def init():
    pygame.init()
    
#    logging.basicConfig(level = logging.WARNING,
#                        filename = SERVER_LOG_FILENAME)

def main():
    init()
    
    print '--------------------------Start server-------------------------'
    server_host = netstream.nethost()
    if server_host.startup(PORT_NUM) != 0:
        logging.critical('Start server host error!')
        sys.exit()
    print '------------------------Start successful-----------------------'
    
    player.init_player(server_host)
    
    server_event_producer = EventProducer(ServerEventIt)
    
    server_r_filter = ServerReceiveFilter(server_host)
    deserial_filter = DeSerialFilter()
    print_filter = TestPrintFilter()
    event_handle_filter = ServerEventHandleFilter(server_event_producer)
    
    serial_filter = SerialFilter()
    server_s_filter = ServerSendFilter(server_host)
    
#    sock_pro_filter = SockProcessFilter(server_host)
    update_filter = ServerUpdateFilter(server_host, player.get_player_center())
    
    dispt = Dispatcher()
    try:

        
        dispt.attach(event.MoveEvent.event_id, server_s_filter)
        dispt.attach(event.MoveEvent.event_id, serial_filter)
        
        dispt.attach(event.ConfirmEvent.event_id, server_s_filter)
        dispt.attach(event.ConfirmEvent.event_id, serial_filter)
        
        dispt.attach(event.PlayerOnLineEvent.event_id, server_s_filter)
        dispt.attach(event.PlayerOnLineEvent.event_id, serial_filter)
        
        dispt.attach(event.FrameEvent.event_id, event_handle_filter)
        dispt.attach(event.FrameEvent.event_id, print_filter)
        dispt.attach(event.FrameEvent.event_id, deserial_filter)
        dispt.attach(event.FrameEvent.event_id, server_r_filter)
        dispt.attach(event.FrameEvent.event_id, update_filter)
    except TypeError,data:
        logging.critical("Can't attach filter!Error msg:%s." % data)
        sys.exit()
        
    e_looper = EventLooper(server_event_producer, dispt)
    
    print '----------------------Start event loop---------------------'
    e_looper.start()

if __name__ == '__main__':
    main()